package com.atnjupt.mybatis.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author Wizarder
 * @create 2022-04-11 16:21
 */
public class MybatisUtil {
    //单例模式，懒汉式
    private static SqlSessionFactory sqlSessionFactory = null;

    /**
     * 获取单个sqlSessionFactory对象
     * @return
     */
    public static SqlSessionFactory getSqlSessionFactory() {
        synchronized (MybatisUtil.class) {
            if (sqlSessionFactory == null) {
                InputStream resourceAsStream = null;
                try {
                    resourceAsStream = Resources.getResourceAsStream("mybatis-config.xml");
                } catch (IOException e) {
                    e.printStackTrace();
                }
                SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
                SqlSessionFactory newSqlSessionFactory = sqlSessionFactoryBuilder.build(resourceAsStream);
                sqlSessionFactory = newSqlSessionFactory;
            }
            return sqlSessionFactory;
        }
    }
}
